<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use App\Constants\Constant;
use App\Model\Foot;
use App\Model\UserScore;
use App\Model\UserScoreDetail;
use Carbon\Carbon;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Amqp\Result;
use Hyperf\DbConnection\Db;
use PhpAmqpLib\Message\AMQPMessage;

/**
 * @Consumer(exchange="score", routingKey="footPublish", queue="footPublish", name ="FootPublishConsumer", nums=1)
 */
class FootPublishConsumer extends ConsumerMessage
{
    public function consumeMessage($data, AMQPMessage $message): string {
        if(UserScoreDetail::query()->where([["user_id",$data['user_id']],["direction",Constant::DIRECTION_INC],["origin",Constant::SCORE_ORIGIN_FOOT_PUBLISH]])->whereDate("add_time",Carbon::now()->toDateString())->exists()){
            return Result::ACK;
        }

        //公开才可获得积分
        $foot = Foot::query()->findOrFail($data['source_id']);
        if($foot->getAttribute("is_public") != Constant::FOOT_PUBLIC){
            return Result::ACK;
        }

        Db::transaction(function () use($data){
            $score = UserScore::query()->find($data['user_id']);
            $score->setAttribute("total",$score->getAttribute("total") + 1);
            $score->setAttribute("available",$score->getAttribute("available") + 1);
            $score->save();

            $score_detail = new UserScoreDetail();
            $score_detail->setAttribute("user_id",$data['user_id']);
            $score_detail->setAttribute("direction",Constant::DIRECTION_INC);
            $score_detail->setAttribute("origin",Constant::SCORE_ORIGIN_FOOT_PUBLISH);
            $score_detail->setAttribute("source_id",$data['source_id']);
            $score_detail->setAttribute("score",1);
            $score_detail->setAttribute("remark","每天发布一条足迹并公开获得1积分");
            $score_detail->save();
        });

        return Result::ACK;
    }
}
